package com.evil.activiti.listener;

import com.evil.activiti.enums.EventTypeEnum;
import com.evil.activiti.util.ActivityUtil;
import com.evil.application.api.RemoteApplicationOrderLogService;
import com.evil.application.pojo.dto.order.log.AddRobotLogReqDTO;
import com.evil.common.activiti.enums.HandleTypeEnum;
import com.evil.common.activiti.enums.NodeTypeEnum;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;

/**
 * 会话自动流转监听器
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Slf4j
@Component("TaskAutoCompleteListener")
@AllArgsConstructor
public class TaskAutoCompleteListener implements TaskListener {

    private final RemoteApplicationOrderLogService remoteApplicationOrderLogService;

    private final TaskService taskService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void notify(DelegateTask delegateTask) {
        String eventName = delegateTask.getEventName();
        String assignee = delegateTask.getAssignee();
        String id = delegateTask.getId();
        String flowId = delegateTask.getTaskDefinitionKey();
        String name = delegateTask.getName();
        Long orderId = delegateTask.getVariable(ActivityUtil.getProcessOrderIdKey(), Long.class);
        log.info("【会话自动流转监听器】，delegateTask.getEventName：{}", eventName);
        log.info("【会话自动流转监听器】，订单id:{}", orderId);
        log.info("【会话自动流转监听器】，delegateTask.getAssignee：{}", assignee);
        log.info("【会话自动流转监听器】，节点id：{}, 节点name:{}", flowId, name);

        if (EventTypeEnum.CREATE.getEvent().equals(eventName)) {
            // 创建
            if (NodeTypeEnum.CARBON_COPY_NODE.getId() == ActivityUtil.restoreFlowNodeType(flowId)) {
                // 抄送节点
                taskService.complete(id, delegateTask.getVariables(), true);

                AddRobotLogReqDTO addRobotLogReqDTO = new AddRobotLogReqDTO();
                addRobotLogReqDTO.setOrderId(orderId);
                addRobotLogReqDTO.setNodeId(ActivityUtil.restoreFlowNodeId(flowId));
                addRobotLogReqDTO.setHandleType(HandleTypeEnum.CARBON.getId());
                remoteApplicationOrderLogService.addOrderLog(addRobotLogReqDTO);
            }
        }
    }
}
